package ruc.TDEngine;

import cn.hutool.core.codec.Base64;
import okhttp3.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

public class TDEngine_Common {
    private static final OkHttpClient CLIENT = new OkHttpClient().newBuilder()
            .readTimeout(50000, TimeUnit.MILLISECONDS)
            .connectTimeout(50000, TimeUnit.MILLISECONDS)
            .writeTimeout(50000, TimeUnit.MILLISECONDS)
            .build();

    public static Response send(Request request){
        try {
            return CLIENT.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static Request getRequest(String sql, String userName, String password, String IP, String port){
        String Authorization = Base64.encode(String.format("%s:%s", userName, password).getBytes(StandardCharsets.UTF_8));
        String URL = String.format("http://%s:%s/rest/sql", IP, port);

        Request request = new Request.Builder()
                .url(URL)
                .method("POST", RequestBody.create(MediaType.parse("text/plain"), sql))
                .addHeader("Authorization", "Basic "+Authorization)
                .addHeader("Content-Type", "text/plain")
                .build();

        return request;
    }

    // TDEngine中不支持truncate和delete * 等操作，所以需要先删除表再建表
    public static void dropAndCreate(String IP, String port, String dbName, String tbName, String userName, String password){
        String s1 = String.format("drop table %s.%s", dbName, tbName);
        Response response = TDEngine_Common.send(TDEngine_Common.getRequest(s1, userName, password, IP, port));
        assert response != null;
        response.close();

        createTable(IP, port, dbName, tbName, userName, password);
    }

    public static void createTable(String IP, String port, String dbName, String tbName, String userName, String password) {
        String s2 = String.format("create table %s.%s(ts timestamp, userInfo binary(128), server binary(128), hostname binary(128), cpu_usage int, memory_usage int, disk_usage int)", dbName, tbName);
        Response response1 = TDEngine_Common.send(TDEngine_Common.getRequest(s2, userName, password, IP, port));
        assert response1 != null;
        response1.close();
    }
}
